<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>富扬数据看板</title>
  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
  <link rel="stylesheet" href="/stylesheets/css/bootstrap.min.css">
  <link rel="stylesheet" href="/stylesheets/css/daterangepicker.css">
  <link rel="stylesheet" href="/stylesheets/css/select2.min.css">
  <link rel="stylesheet" href="/stylesheets/css/AdminLTE.min.css">
  <link rel="stylesheet" href="/stylesheets/skins/_all-skins.min.css">
  <style>
    .alert{
      padding: 8px;
      position: fixed;
      z-index: 2000;
      width: 300px;
      top: 30px;
      left:0; right:0;
      margin: 0 auto;
    }
    .alert p{
      text-align: center;
      font-size: 14px;
    }
    .close{
      font-size: 16px;
    }
    #example button{
      text-decoration: underline;
    }
    #example button, #example a{
      font-weight: bold;
      color: #19568b;
      border: none;
      background: none;
    }
    #example .noSelect button{
      font-weight: normal;
      font-size: 12px;
      color: #4d9ecc;
      text-decoration: underline;
    }
    #example a:hover{
      cursor: pointer;
    }
    #example .setting button{
      text-decoration: none;
    }
    .locking{
      color: #aaa;
    }
    #example .locking button{
      color: #aaa;
    }
    #example .locking button span{
      color: #aaa;
    }
    #example .locking .isLock{
      color: #19568b;
    }

    #exampleInputFile{
      display: inline-block;
      width: 180px;
    }
    .keySearchBox{
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 330px;
    }
    .keySearchBox span{width: 100px;}
    .keySearchBox .keySearch{width: 150px;}
    .keySearchBox .keySearchBtn{width: 50px;}

    .content-header>h1>.breadcrumb {
      background: transparent;
      margin-top: 0;
      margin-bottom: 0;
      font-size: 12px;
      padding: 7px 5px;
      border-radius: 2px;
      display: inline-block;
    }
    .h-30{
      height:30px;
    }
    .box-header{
      padding-bottom: 0;
    }
    .box{
      margin-bottom: 0;
    }

    .loading{
      opacity: 0.5;
      position: absolute;
      left: 50%; top:50%;
      width: 100px; height: 100px;
      margin: -50px 0 0 -50px;
    }
  </style>
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
  <%- include("./public/header.ejs") %>

  <%- include("./public/aside.ejs") %>

  <div id="alert"></div>

  <div class="content-wrapper">
    <section class="content-header">
      <h1>
        订单管理
        <ol class="breadcrumb">
          <li><a href="/"><i class="glyphicon glyphicon-dashboard"></i>首页</a></li>
          <li class="active">订单管理</li>
        </ol>
      </h1>
    </section>
    <section class="content">
      <div class="row">
        <div class="col-md-12">
          <div class="box">
            <div class="box-header">
              <a href="/order/add" class="btn btn-info btn-xs">添加订单</a>
              <a class="btn btn-default btn-xs" data-toggle="modal" data-target="#modal-file">导入订单</a>
            </div>
            <div class="box-body">
              <div class="row" style="margin-bottom: 5px;">
                <div class="col-md-5">
                  <div class="">
                    <label>请选择日期:</label>
                    <div class="input-group">
                      <div class="input-group-addon h-30">
                        <i class="glyphicon glyphicon-th"></i>
                      </div>
                      <input type="text" class="form-control pull-right h-30" id="reservation">
                    </div>
                  </div>
                </div>
                <button class="btn btn-info btn-sm col-md-1 search" style="margin-top: 24px;">查询</button>
                <button class="btn btn-info btn-sm col-md-1 searchAll" style="margin-top: 24px;margin-left: 10px;">查询当月</button>
                <button class="btn btn-default btn-sm col-md-1 export" style="margin-top: 24px;margin-left: 10px;">导出查询</button>
                <button class="btn btn-default btn-sm col-md-1 lockingBtn" style="margin-top: 24px;margin-left: 10px;">锁定查询</button>
                <button class="btn btn-default btn-sm col-md-1 lockingBtn2" style="margin-top: 24px;margin-left: 10px;">解锁查询</button>
              </div>
              <div class="row">
                <div class="col-md-8">
                  统计：当前共 <span class="rowCount">0</span> 行，本币金额合计：<span class="LocalCurrencyAmountCount">0</span>，本币折扣后合计：<span class="LocalCurrencyAmountAfterDiscountCount">0</span>
                </div>
                <div class="col-md-4">
                  <label class="keySearchBox" style="margin-left: auto;">
                    <span>搜索订单人员:</span>
                    <input type="search" class="form-control input-sm keySearch" placeholder="">
                    <input type="button" class="btn btn-info btn-sm keySearchBtn" value="确定">
                  </label>
                </div>
              </div>
              <div id="example" class="ag-theme-quartz" style="height: calc(100vh - 278px)">
                <img src="/images/loading.gif" alt="" class="loading">
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  </div>

  <!-- <%- include("./public/footer.ejs") %> -->
</div>

<!-- 选择员工 -->
<div class="modal fade" id="modal-user">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">请选择</h4>
      </div>
      <div class="modal-body">
        <select class="form-control selectUser" style="width: 100%;"></select>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default pull-left" data-dismiss="modal">关闭</button>
        <button type="button" class="btn btn-primary submit" data-dismiss="modal">提交</button>
      </div>
    </div>
  </div>
</div>

<!-- 选择文件 -->
<div class="modal fade" id="modal-file">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <form action="/order/import" method="post" enctype="multipart/form-data" role="form">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title">请选择</h4>
        </div>
        <div class="modal-body">
          <input type="file" id="exampleInputFile" name="order">
          <a href="/order/exportTemp" class="btn btn-default btn-xs" style="margin-left: 10px;">导出模板</a>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default pull-left" data-dismiss="modal">关闭</button>
          <button type="submit" class="btn btn-primary">提交</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script src="/javascripts/jquery.min.js"></script>
<script src="/javascripts/bootstrap.min.js"></script>
<script src="/javascripts/moment.min.js"></script>
<script src="/javascripts/daterangepicker.js"></script>
<script src="/javascripts/ag-grid-community.min.js"></script>
<script src="/javascripts/select2.full.min.js"></script>
<script src="/javascripts/adminlte.min.js"></script>

<script>

  class CustomButtonComponent {
    init(params) {
      this.eGui = document.createElement("div");
      let eButton = document.createElement("button");
      eButton.className = "btn-simple " + params.colDef.field;
      eButton.innerText = params.value;
      eButton.dataset.toggle = "modal";
      eButton.dataset.target = "#modal-user";
      eButton.dataset.oid = params.data.oId;
      eButton.dataset.type = params.colDef.field;
      if (params.data.locking) {
        eButton.disabled = true;
        eButton.style.color = "#ccc"
      }else{
        eButton.disabled = false;
        eButton.style.color = ""
      }
      this.eGui.appendChild(eButton);
    }
    getGui() {
      return this.eGui
    }
    refresh() {
      return true
    }
    destroy() {
    }
  }

  class SettingButtonComponent {
    init(params) {
      this.eGui = document.createElement("div");
      
      this.eGui.innerHTML = `
        <button class="order_set" ${params.data.locking ? 'disabled' : ''} style="color:${params.data.locking ? '#ccc' : ''}" data-href="/order/add?oId=${params.data.oId}&OrderClerk=${params.data.OrderClerk}">修改</button>
        <a class="isLock" href="/order/locking?oId=${params.data.oId}&state=${params.data.locking ? 0 : 1}">${params.data.locking ? '解锁' : '锁定'}</a>
        <button class="order_del" ${params.data.locking ? 'disabled' : ''} style="color:${params.data.locking ? '#ccc' : ''}" data-href="/order/delete?oId=${params.data.oId}">删除</button>`
    }
    getGui() {
      return this.eGui
    }
    refresh() {
      return true
    }
    destroy() {
    }
  }

  var ws = new WebSocket("ws://106.54.246.120:3000/dashboard");
  ws.onopen = function (evt) {
    ws.send("");
  };
  // ws.onclose = function (evt) {
  //   console.log("Connection closed.");
  // };

  const userData = <%- JSON.stringify(userData) %>;
  const orderData = <%- JSON.stringify(orderData) %>;
  const exchangeRateData = <%- JSON.stringify(exchangeRateData) %>;

  //定义表格列
  var columnDefs = [
    { headerName: '订单日期', field: 'OrderDate', pinned: 'left', width: 130, tooltipField: "OrderDate", 
    valueGetter: params => {
      const date = params.data.OrderDate.split("/");
      if(date[0] && params.node.rowPinned !== "bottom"){
        return date[0] + "/" + cz(date[1]) + "/" + cz(date[2]);
      }else{
        return "";
      }
    } },
    { headerName: '核算号', field: 'AccountingNo', pinned: 'left', width: 130, tooltipField: "AccountingNo" },
    { headerName: '客户名称', pinned: 'left', width: 140, valueGetter: (params) => params.data.CustomerName && params.data.CustomerName.cName, tooltipValueGetter: (params) => params.data.CustomerName && params.data.CustomerName.cName, filter: "agTextColumnFilter" },
    { headerName: '船名', field: 'ShipName', width: 130, tooltipField: "ShipName" },
    { headerName: '港口', field: 'ShipPort', width: 130, tooltipField: "ShipPort" },
    { headerName: '币种', width: 90, valueGetter: params => exchangeRateData.find(v => params.data.Currency === v.eId)?.currency },
    { headerName: '订单原币金额', field: 'OriginalCurrencyAmount', width: 140 },
    { headerName: '订单本币金额', field: 'LocalCurrencyAmount', width: 140 },
    { headerName: '原币折扣后金额', field: 'OriginalCurrencyAmountAfterDiscount', width: 150 },
    { headerName: '本币折扣后金额', field: 'LocalCurrencyAmountAfterDiscount', width: 150 },
    { headerName: '订单员', width: 130, valueGetter: (params) => params.data.OrderClerk || '<span>请选择</span>',
      field: "OrderClerk", 
      cellRenderer: CustomButtonComponent,
      cellClass: params => params.value === '请选择' ? "noSelect" : '',
    },
    { headerName: '市场员', width: 130, valueGetter: (params) => params.data.Marketer || '请选择',
      field: "Marketer", 
      cellRenderer: CustomButtonComponent,
      cellClass: params => params.value === '请选择' ? "noSelect" : '',
    },
    { headerName: '报价员', width: 130, valueGetter: (params) => params.data.Quoter || '请选择',
      field: "Quoter", 
      cellRenderer: CustomButtonComponent,
      cellClass: params => params.value === '请选择' ? "noSelect" : '',
    },
    { headerName: '采购员', width: 130, valueGetter: (params) => params.data.Purchasing || '请选择',
      field: "Purchasing", 
      cellRenderer: CustomButtonComponent,
      cellClass: params => params.value === '请选择' ? "noSelect" : '',
    },
    { headerName: '仓库员', width: 130, valueGetter: (params) => params.data.Warehouse || '请选择',
      field: "Warehouse", 
      cellRenderer: CustomButtonComponent,
      cellClass: params => params.value === '请选择' ? "noSelect" : '',
    },
    { headerName: '供船员', width: 130, valueGetter: (params) => params.data.ProvideBoat || '请选择',
      field: "ProvideBoat", 
      cellRenderer: CustomButtonComponent,
      cellClass: params => params.value === '请选择' ? "noSelect" : '',
    },
    { headerName: '财务员', width: 130, valueGetter: (params) => params.data.Financial || '请选择',
      field: "Financial", 
      cellRenderer: CustomButtonComponent,
      cellClass: params => params.value === '请选择' ? "noSelect" : '',
    },
    { headerName: '物流员', width: 130, valueGetter: (params) => params.data.Logistics || '请选择',
      field: "Logistics", 
      cellRenderer: CustomButtonComponent,
      cellClass: params => params.value === '请选择' ? "noSelect" : '',
    },
    {
      headerName: '操作', width: 150, 
      cellRenderer: SettingButtonComponent,
    },
  ];

  //将列和数据赋给gridOptions 
  var gridOptions = {
    tooltipShowDelay: 500,
    columnDefs: columnDefs,
    rowData: [],
    defaultColDef: {
      filter: true,
    },
    getRowStyle: function (params) {
      if (params.data.locking) {
        return { 'color': '#ccc' };
      }
    },
    onGridReady: function () {
      $(".loading").hide();
      getCount( orderData );
      gridApi.setGridOption("rowData", orderData);
      setTimeout( ()=> $(".ag-body-viewport")[0].scrollTop = sessionStorage.getItem("top") || 0, 0 );
    },
  };
  let gridApi = null;
  setTimeout(()=>{
    gridApi = agGrid.createGrid(document.querySelector("#example"), gridOptions);
  });

  $('#example').on("click", ".ag-body-viewport", function(){
    sessionStorage.setItem("top", this.scrollTop)
  })

  
  let type = '';
  let oId = '';
  $('#example').on("click", ".OrderClerk", function(){
    type = 'OrderClerk';
    oId = this.dataset.oid;
    $('.selectUser').val('').trigger("change");
  })
  $('#example').on("click", ".Marketer", function(){
    type = 'Marketer';
    oId = this.dataset.oid;
    $('.selectUser').val('').trigger("change");
  })
  $('#example').on("click", ".Quoter", function(){
    type = 'Quoter';
    oId = this.dataset.oid;
    $('.selectUser').val('').trigger("change");
  })
  $('#example').on("click", ".Purchasing", function(){
    type = 'Purchasing';
    oId = this.dataset.oid;
    $('.selectUser').val('').trigger("change");
  })
  $('#example').on("click", ".Warehouse", function(){
    type = 'Warehouse';
    oId = this.dataset.oid;
    $('.selectUser').val('').trigger("change");
  })
  $('#example').on("click", ".ProvideBoat", function(){
    type = 'ProvideBoat';
    oId = this.dataset.oid;
    $('.selectUser').val('').trigger("change");
  })
  $('#example').on("click", ".Financial", function(){
    type = 'Financial';
    oId = this.dataset.oid;
    $('.selectUser').val('').trigger("change");
  })
  $('#example').on("click", ".Logistics", function(){
    type = 'Logistics';
    oId = this.dataset.oid;
    $('.selectUser').val('').trigger("change");
  })

  // 选择员工
  $('.selectUser').select2({
    allowClear: true,
    placeholder: '请选择',
    data: [{
      id: '', text: ''
    }, ...userData.map(v=>({
      id: v.uId,
      text: v.employeesName
    }))]
  })
  
  // 提交选择员工
  $(".submit").click(function(){
    const uId = $('.selectUser').val();
    $.ajax({
      url: '/order/setUser',
      type: 'post',
      data: {
        uId, type, oId
      }
    }).then(res=>{
      ws.send("");
      alert({type:'success', msg:'操作成功'});
      const index = orderData.findIndex(v=>v.oId===oId)
      if(index !== -1){
        orderData[index][type] = userData.find(v=>v.uId===uId).employeesName;
        $(".loading").hide();
        getCount( orderData );
        gridApi.setGridOption("rowData", orderData);
        setTimeout( ()=> $(".ag-body-viewport")[0].scrollTop = sessionStorage.getItem("top") || 0, 0 );
      }
    }).catch(code=>{
      console.error( code );
      alert({type:'danger', msg:JSON.stringify(code)})
    })
  })

  const date = {};
  if(location.search){
    location.search.slice(1).split("&").forEach(val=>{
      date[val.split("=")[0]] = val.split("=")[1];
    });
  }else{
    date.startDate = getMonthDate()[0];
    date.endDate = getMonthDate()[1];
  }

  $('#reservation').daterangepicker({
    startDate: date.startDate || 0,
    endDate: date.endDate || 0,
    locale:{
      format: 'YYYY/MM/DD',
      separator: " - ",
      applyLabel: '确定',
      cancelLabel: '取消',
      fromLabel: '起始时间',
      toLabel: '结束时间',
      customRangeLabel: '自定义',
      daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
      monthNames: ['一月', '二月', '三月', '四月', '五月', '六月','七月', '八月', '九月', '十月', '十一月', '十二月'],
      firstDay: 1
    }
  });

  if(location.search){
    $(".export").removeAttr("disabled");
    $(".lockingBtn").removeAttr("disabled");
    $(".lockingBtn2").removeAttr("disabled");
  }else{
    $(".export").attr("disabled", "disabled");
    $(".lockingBtn").attr("disabled", "disabled");
    $(".lockingBtn2").attr("disabled", "disabled");
  }

  $(".locking button").attr("disabled", "disabled");

  let searchKey = '';
  $(".search").click(function(){
    const d = $('#reservation').val().split(" - ")
    searchKey = `?startDate=${d[0].replace(/\//g,"-")}&endDate=${d[1].replace(/\//g,"-")}`;
    location.assign(`/order/search` + searchKey);
  })
  
  $(".searchAll").click(function(){
    searchKey = '';
    location.assign(`/order`);
  })
  
  $(".export").click(function(){
    location.assign(`/order/export` + location.search);
  })
  
  $(".lockingBtn").click(function(){
    location.assign(`/order/locking?state=1&` + location.search.slice(1));
  })

  $(".lockingBtn2").click(function(){
    location.assign(`/order/locking?state=0&` + location.search.slice(1));
  })

  $('#example').on("click", ".order_set", function(){
    location.assign(this.dataset.href);
  })
  $('#example').on("click", ".order_del", function(){
    location.assign(this.dataset.href);
  })

  $(".keySearch").on("keydown",function(e){
    if(e.keyCode === 13){
      searchContent( $(this).val() );
    }
  })
  $(".keySearchBtn").on("click",function(e){
    searchContent( $(".keySearch").val() );
  })

  function searchContent(k){
    const searchOrder = orderData.filter(val=>{
      return Object.values(val).join().includes( k )
    })
    
    $(".loading").hide();
    getCount( searchOrder );
    gridApi.setGridOption("rowData", searchOrder);

    $(".keySearch").val("");
  }

  function alert(ops){
    const {type='info', msg='提示信息'} = ops;
    const innerHTML = `<div class="alert alert-${type}"><span class="close" data-dismiss="alert" aria-hidden="true">&times;</span><p>${msg}!</p></div>`;
    if($("#alert").html()){
      $("#alert").show(100);
    }else{
      $("#alert").html(innerHTML);
    }

    clearTimeout($("#alert").t);
    $("#alert").t = setTimeout(()=>{
      $("#alert").hide(100);
    }, 2000)
    return $("#alert");
  }

  function cz(v){
    return v && v.length<2 ? "0"+v : v;
  }

  function getCount( data ){
    $(".LocalCurrencyAmountAfterDiscountCount").html( '￥' + data.reduce((prev,val)=>prev+val.LocalCurrencyAmountAfterDiscount, 0).toFixed(2) )
    $(".LocalCurrencyAmountCount").html( '￥' + data.reduce((prev,val)=>prev+val.LocalCurrencyAmount, 0).toFixed(2) )
    $(".rowCount").html( data.length )
  }

  function getMonthDate(m){
    const d = new Date();
    const year = d.getFullYear();
    const month = m || (d.getMonth() + 1);
    let end = 30;
    switch(month-0){
      case 1:
      case 3:
      case 5:
      case 7:
      case 8:
      case 10:
      case 12:
        end = 31;break;
      case 4:
      case 6:
      case 9:
      case 11:
        end = 30;break;
      case 2:
        if( year%4===0 && year%100!==0 || year%400 === 0 ){
          end = 29;
        }else{
          end = 28;
        }
    }
    return [ year + "/" + month + "/" + 1, year + "/" + month + "/" + end ];
  }

</script>
</body>
</html>
